<template>
  <!-- 安全管理制度 -->
  <div class="reviewrecord">
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
      >

        <!-- 左上方菜单栏 -->
        <template slot="menuLeft">
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            plain
            v-if="permission.reviewrecord_delete"
            @click="handleDelete">
            删 除
          </el-button>
          <el-button
            type="warning"
            size="small"
            plain
            icon="el-icon-download"
            @click="handleExport">
            导 出
          </el-button>
        </template>

        <!-- 评审附件表单自定义 -->
        <template slot="psfjForm">
          <div>
            <el-upload
              v-if="dialogType !== 'view'"
              action="/api/fileManager/upload/file"
              :headers="SetHeaders"
              :file-list="psfjFileList"
              :before-upload="beforeUploadPSFJ"
              :on-remove="handleRemovePSFJ"
              :on-success="uploadPSFJSuccess"
            >
              <el-button size="small" type="primary" icon="el-icon-document">选择文件</el-button>
            </el-upload>

            <a
              v-else
              v-for="(item, index) in psfjFileList"
              :key="index"
              :href="downloadHead + item.response.data.id"
              style="color:#409EFF"
            >
              <i class="el-icon-download" style="margin-right:5px;"></i>下载文件（{{ item.name }}）
            </a>
          </div>
        </template>

        <!-- 状态表格自定义 -->
        <template slot="status" slot-scope="scope">
          <span>{{formatStatus(scope.row)}}</span>
        </template>

        <!-- 附件表格自定义 -->
        <template slot="psfj" slot-scope="scope">
          <div class="enclosure_div">
            <a :href="downloadHead + scope.row['psfj']" v-if="scope.row['psfj'] !== '' && scope.row['psfj'] !== undefined">
              <i class="el-icon-download"></i>下载附件
            </a>
            <span v-else>-</span>
          </div>
        </template>

        <!-- 审批表格自定义 -->
        <template slot="approve" slot-scope="scope">
          <div>
            <el-button
              v-if="scope.row['auditPermissions']"
              type="success"
              size="mini"
              @click="handleExamine(scope.row)">
              审 核
            </el-button>
            <el-button
              v-if="scope.row['approvalPermissions']"
              type="warning"
              size="mini"
              @click="handleApprove(scope.row)">
              批 准
            </el-button>
            <span v-if="!scope.row['auditPermissions'] && !scope.row['approvalPermissions']">-</span>
          </div>
        </template>

        <!-- 评审表格自定义 -->
        <template slot="review" slot-scope="scope">
          <div>
            <el-button
              type="danger"
              size="mini"
              @click="handleReview(scope.row)">
              提交评审
            </el-button>
          </div>
        </template>

      </avue-crud>

      <!-- 审核、批准弹窗 -->
      <el-dialog 
        :title="dialogTitle"
        append-to-body
        :visible.sync="updateDialog"
        :close-on-click-modal="false" 
        :before-close="closeUpdateDialog"
        width="60%"
        class="examine_approve_dialog"
      > 

        <!-- 内容 -->
        <avue-form 
          ref="updateForm" 
          v-model="updateObj" 
          :option="updateOption" 
          @submit="confirmExamineOrApprove"
        >

          <!-- 评审附件表单自定义 -->
          <template slot="psfj">
            <div>
              <span v-if="psfjFileList === undefined || psfjFileList.length === 0">-</span>

              <a 
                v-else 
                v-for="(item, index) in psfjFileList"
                :key="index"
                :href="downloadHead + item.response.data.id"
                style="color:#409EFF"
              >
                <i class="el-icon-download" style="margin-right:5px;"></i>下载文件（{{ item.name }}）
              </a>
            </div>
          </template>

          <!-- 自定义按钮 -->
          <template slot="menuForm">
            <el-button 
              size="small"
              icon="el-icon-close"
              @click="closeUpdateDialog()">
              取 消
            </el-button>
          </template>
        </avue-form>

      </el-dialog>

      <!-- 添加评审弹窗 -->
      <el-dialog 
        :title="添加评审"
        append-to-body
        :visible.sync="addReviewDialog"
        :close-on-click-modal="false" 
        :before-close="closeAddReviewDialog"
        width="60%"
        class="add_review_dialog"
      > 

        <el-row>
          <el-col :span="24">
            <el-button 
              type="success"
              size="small"  
              icon="el-icon-plus"
              @click="addReviewPerson()">
              添加评审人员
            </el-button>
          </el-col>
        </el-row>

        <!-- 按钮 -->
        <div class="add_review_footer">
          <el-button 
            type="primary"
            size="small"
            @click="confirmAddReview()">
            确 定
          </el-button>
          <el-button 
            size="small"
            @click="closeAddReviewDialog()">
            取 消
          </el-button>
        </div>

      </el-dialog>

    </basic-container>
  </div>
</template>

<script>
import {
  getList,
  add,
  update,
  remove,
  modifyStatus,
  getStatusList
} from "@/api/securitysystemmanagement/reviewrecord";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";

export default {
  data() {
    return {
      form: {},
      query: {},
      data: [],
      loading: true,
      selectionList: [],
      page: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 4,
        border: true,
        index: false,
        selection: true,
        viewBtn: true,
        refreshBtn: true,
        columnBtn: false,
        dialogClickModal: false,
        menuWidth: 200,
        column: [
          {
            label: "安全制度",
            prop: "reviewObjId",
            span: 24,
            hide: true,
            type: "tree",
            dicUrl: "/api/securitySystemManagement/mgtsystem/approvalOfSafetyManagementSystem",
            props: {
              label: "zdmc",
              value: "id",
            },
            rules: [{
              required: true,
              message: "请选择安全管理制度",
              trigger: "change"
            }]
          },
          {
            label: "安全制度",
            prop: "systemTitle",
            align: "center",
            display: false
          },
          {
            label: "评审主题",
            prop: "pszt",
            span: 24,
            align: "center",
            search: true,
            rules: [{
              required: true,
              message: "请输入评审主题",
              trigger: "blur"
            }]
          },
          {
            label: "评审日期",
            prop: "psrq",
            span: 24,
            align: "center",
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
            width: 90
          },
          {
            label: "地点",
            prop: "dd",
            span: 24,
            align: "center"
          },
          {
            label: "评审依据",
            prop: "psyj",
            span: 24,
            hide: true
          },
          {
            label: "评审范围",
            prop: "psfw",
            span: 24,
            hide: true
          },
          {
            label: "参评人员",
            prop: "cpry",
            span: 24,
            hide: true
          },
          {
            label: "评审纪要",
            prop: "psjy",
            span: 24,
            type: "textarea",
            maxlength: 150,
            hide: true
          },
          {
            label: "评审结论",
            prop: "psjl",
            span: 24,
            align: "center"
          },
          {
            label: "审核人",
            prop: "shren",
            hide: true,
            type: "select",
            dicUrl: "/api/riskPoint/riskmanagement/getInternalStaff",
            props: {
              label: "realName",
              value: "id",
            },
            rules: [{
              required: true,
              message: "请选择审核人",
              trigger: "change"
            }]
          },
          {
            label: "批准人",
            prop: "spren",
            hide: true,
            type: "select",
            dicUrl: "/api/riskPoint/riskmanagement/getInternalStaff",
            props: {
              label: "realName",
              value: "id",
            },
            rules: [{
              required: true,
              message: "请选择批准人",
              trigger: "change"
            }]
          },
          {
            label: "评审附件",
            prop: "psfj",
            span: 24,
            align: "center",
            width: 100,
            slot: true,
            formslot: true
          },
          {
            label: "状态",
            display: false,
            prop: "status",
            align: "center",
            width: 100,
            slot: true
          },
          {
            label: "审批",
            display: false,
            prop: "approve",
            align: "center",
            width: 100,
            slot: true
          },
          // {
          //   label: "评审",
          //   display: false,
          //   prop: "review",
          //   align: "center",
          //   width: 110,
          //   slot: true
          // }
        ]
      },
      // 评审附件
      downloadHead: "/api/fileManager/download/",
      SetHeaders: { "Blade-Auth": getToken() },
      dialogType: "",
      psfjFileList: [],
      statusObj: {},
      // 审核、批准弹窗
      updateDialogType: "",
      examineStr: "EXAMINE",
      approveStr: "APPROVE",
      dialogTitle: "",
      updateDialog: false,
      updateObj: {},
      // 提交评审弹窗
      addReviewDialog: false,
      addReviewId: ""
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    // 按钮权限
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.reviewrecord_add, false),
        viewBtn: this.vaildData(this.permission.reviewrecord_view, false),
        delBtn: this.vaildData(this.permission.reviewrecord_delete, false),
        editBtn: this.vaildData(this.permission.reviewrecord_edit, false)
      };
    },

    // 勾选项id
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },

    updateOption() {
      return {
        size: "small",
        submitText: "确 定",
        mockBtn: false,
        printBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "安全制度",
            prop: "reviewObjId",
            disabled: true,
            span: 24,
            type: "tree",
            multiple: true,
            dicUrl: "/api/securitySystemManagement/mgtsystem/approvalOfSafetyManagementSystem",
            props: {
              label: "zdmc",
              value: "id",
            },
            rules: [{
              required: true,
              message: "请选择安全管理制度",
              trigger: "change"
            }]
          },
          {
            label: "评审主题",
            prop: "pszt",
            disabled: true,
            span: 24,
            rules: [{
              required: true,
              message: "请输入评审主题",
              trigger: "blur"
            }]
          },
          {
            label: "评审日期",
            prop: "psrq",
            disabled: true,
            span: 24,
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd"
          },
          {
            label: "地点",
            prop: "dd",
            disabled: true,
            span: 24
          },
          {
            label: "评审依据",
            prop: "psyj",
            disabled: true,
            span: 24
          },
          {
            label: "评审范围",
            prop: "psfw",
            disabled: true,
            span: 24
          },
          {
            label: "参评人员",
            prop: "cpry",
            disabled: true,
            span: 24
          },
          {
            label: "评审纪要",
            prop: "psjy",
            disabled: true,
            span: 24,
            type: "textarea",
            maxlength: 150
          },
          {
            label: "评审结论",
            prop: "psjl",
            disabled: true,
            span: 24
          },
          {
            label: "评审附件",
            prop: "psfj",
            disabled: true,
            span: 24,
            slot: true,
            formslot: true
          },
          {
            label: "审核人",
            prop: "shren",
            disabled: true,
            type: "select",
            dicUrl: "/api/riskPoint/riskmanagement/getInternalStaff",
            props: {
              label: "realName",
              value: "id",
            },
            rules: [{
              required: true,
              message: "请选择审核人",
              trigger: "change"
            }]
          },
          {
            label: "批准人",
            prop: "spren",
            disabled: true,
            type: "select",
            dicUrl: "/api/riskPoint/riskmanagement/getInternalStaff",
            props: {
              label: "realName",
              value: "id",
            },
            rules: [{
              required: true,
              message: "请选择批准人",
              trigger: "change"
            }]
          },
          {
            label: "部门审核",
            prop: "deptExamine",
            disabled: true,
            type: "radio",
            display: false,
            dicData: [{
              label: "同意",
              value: 1
            }, {
              label: "不同意",
              value: 2
            }],
            rules: [{
              required: true,
              message: "请选择部门审核意见",
              trigger: "change"
            }]
          },
          {
            label: "领导批准",
            prop: "leaderApprove",
            disabled: true,
            type: "radio",
            display: false,
            dicData: [{
              label: "同意",
              value: 1
            }, {
              label: "不同意",
              value: 2
            }],
            rules: [{
              required: true,
              message: "请选择领导批准意见",
              trigger: "change"
            }]
          }
        ]
      } 
    }
  },
  mounted() {
    this.initData();
  },
  methods: {

    // 初始化页面
    initData() {
      getStatusList().then(res => {
        this.statusObj = {};
        res.data.data.forEach(item => {
          this.statusObj[item.dictKey] = item.dictValue;
        });
      }).then(() => {
        this.onLoad(this.page);
      });
    },

    // 格式化状态列
    formatStatus(row) {
      var zt = row.zt;
      return this.statusObj[zt] || "-";
    },

    // 点击导出按钮
    handleExport() {
      this.$confirm("是否导出制度评审记录?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let pszt = this.query.pszt === undefined || this.query.pszt === null ? "" : this.query.pszt;
        let type = "system";
        window.open(`/api/securitySystemManagement/reviewrecord/export?${this.website.tokenHeader}=${getToken()}&pszt=${pszt}&type=${type}`);
      });
    },

    // 新增
    rowSave(row, done, loading) {
      for (let key in row) {
        if (key.indexOf("$") >= 0) {
          delete row[key];
        }
      }
      // row.reviewObjId = row.reviewObjId.join(",");
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          loading();
          window.console.log(error);
        }
      );
    },

    // 修改
    rowUpdate(row, index, done, loading) {
      for (let key in row) {
        if (key.indexOf("$") >= 0) {
          delete row[key];
        }
      }
      // row.reviewObjId = typeof row.reviewObjId === "object" ? row.reviewObjId.join(",") : row.reviewObjId;
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          loading();
          console.log(error);
        }
      );
    },

    // 删除一条
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },

    // 删除多条
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },

    // 打开新增、查看、编辑弹窗前
    beforeOpen(done, type) {
      if(type === "edit") {
        if(!this.form.editPermissions) {
          this.$message.warning("当前制度评审记录不可编辑!");
          return;
        }
      }
      this.dialogType = type;
      this.psfjFileList = [];
      if (["edit", "view"].includes(type)) {
        if (this.form.psfj && this.form.bladeFiles && JSON.stringify(this.form.bladeFiles) !== "{}") {
          this.psfjFileList.push({
            name: this.form.bladeFiles.fileName,
            response: {
              code: 200,
              msg: "操作成功",
              success: true,
              data: this.form.bladeFiles
            }
          });
        }
      }
      done();
    },

    // 清空搜索条件
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    // 搜索条件改变
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },

    // 勾选
    selectionChange(list) {
      this.selectionList = list;
    },

    // 清空勾选
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    // 更换页数
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },

    // 更换每页显示数量
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },

    // 刷新
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    // 加载数据
    onLoad(page, params = {}) {
      this.loading = true;
      this.query["type"] = "system";
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },

    /**
     * 上传评审附件
     */

    // 上传评审附件前
    beforeUploadPSFJ(file) {
      console.log(file);
      var isLimit = this.psfjFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一个评审附件!");
      }
      return isLimit;
    },

    // 上传评审附件成功
    uploadPSFJSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.psfjFileList = fileList;
      this.form.psfj = response.data.id;
    },

    // 删除评审附件
    handleRemovePSFJ(file, fileList) {
      this.psfjFileList = fileList;
      this.form.psfj = "";
    },

    // 格式化审核、批准、修订弹窗表单数据
    formatUpdateForm(row) {
      var data = {};
      for(var key in row) {
        data[key] = row[key];
      }
      return data;
    },

    // 获取部门审核、领导批准字段值
    formatExamineApproveValue(obj) {
      if(obj.zt === 0) {
        obj["deptExamine"] = "";
        obj["leaderApprove"] = "";
      } else if(obj.zt === 1) {
        obj["deptExamine"] = 1;
        obj["leaderApprove"] = "";
      } else if(obj.zt === 2) {
        obj["deptExamine"] = 2;
        obj["leaderApprove"] = "";
      } else if(obj.zt === 3) {
        obj["deptExamine"] = 1;
        obj["leaderApprove"] = 1;
      } else if(obj.zt === 4) {
        obj["deptExamine"] = 1;
        obj["leaderApprove"] = 2;
      } else {
        obj["deptExamine"] = "";
        obj["leaderApprove"] = "";
      }
    },

    // 打开审核弹窗
    handleExamine(row) {
      this.updateDialogType = this.examineStr;
      this.updateDialog = true;
      this.dialogTitle = "审核制度评审";
      this.updateObj = this.formatUpdateForm(row);
      this.psfjFileList = [];
      if (row.psfj && row.bladeFiles && JSON.stringify(row.bladeFiles) !== "{}") {
        this.psfjFileList.push({
          name: row.bladeFiles.fileName,
          response: {
            code: 200,
            msg: "操作成功",
            success: true,
            data: row.bladeFiles
          }
        });
      }
      this.updateOption.column.forEach(item => {
        if(item.prop === "deptExamine") {
          item.display = true;
          item.disabled = false;
        }
        if(item.prop === "leaderApprove") {
          item.display = false;
          item.disabled = true;
        }
      });
      this.formatExamineApproveValue(this.updateObj);
    },

    // 打开批准弹窗
    handleApprove(row) {
      this.updateDialogType = this.approveStr;
      this.updateDialog = true;
      this.dialogTitle = "批准制度评审";
      this.updateObj = this.formatUpdateForm(row);
      this.psfjFileList = [];
      if (row.psfj && row.bladeFiles && JSON.stringify(row.bladeFiles) !== "{}") {
        this.psfjFileList.push({
          name: row.bladeFiles.fileName,
          response: {
            code: 200,
            msg: "操作成功",
            success: true,
            data: row.bladeFiles
          }
        });
      }
      this.updateOption.column.forEach(item => {
        if(item.prop === "deptExamine") {
          item.display = true;
          item.disabled = true;
        }
        if(item.prop === "leaderApprove") {
          item.display = true;
          item.disabled = false;
        }
      });
      this.formatExamineApproveValue(this.updateObj);
    },

    // 关闭、取消审核&批准&修订弹窗
    closeUpdateDialog() {
      this.updateObj = {};
      this.updateDialogType = "";
      this.updateDialog = false;
      this.dialogTitle = "";
    },

    // 确定审核、批准
    confirmExamineOrApprove() {
      if(this.updateDialogType === this.examineStr) {
        this.confirmExamine();
      } else if(this.updateDialogType === this.approveStr) {
        this.confirmApprove();
      }
    },

    // 确认审核
    confirmExamine() {
      this.$refs.updateForm.validate((vaild,done)=>{
        if(vaild){
          modifyStatus(this.updateObj.id, this.updateObj.zt, this.updateObj.deptExamine).then(res => {
            if(res.data.success) {
              done();
              this.closeUpdateDialog();
              this.page.currentPage = 1;
              this.onLoad(this.page);
            }
          });
        }
      })
    },

    // 确认批准
    confirmApprove() {
      this.$refs.updateForm.validate((vaild,done)=>{
        if(vaild){
          modifyStatus(this.updateObj.id, this.updateObj.zt, this.updateObj.leaderApprove).then(res => {
            if(res.data.success) {
              done();
              this.closeUpdateDialog();
              this.page.currentPage = 1;
              this.onLoad(this.page);
            }
          });
        }
      })
    },

    // 点击提交评审按钮
    handleReview(row) {
      this.addReviewDialog = true;
    },

    // 关闭、取消提交评审弹窗
    closeAddReviewDialog() {
      this.addReviewDialog = false;
      this.addReviewId = "";
    },

  }
};
</script>

<style lang="scss" scpoed>
.reviewrecord {
  .enclosure_div {
    a {
      font-size: 12px;
      color: #409eff;

      i {
        margin-right: 5px;
      }
    }
  }
}

.examine_approve_dialog {
  .avue-form__menu--center {
    text-align: center;
  }
}

.add_review_footer {
  text-align: center;
  margin-top: 15px;

  .el-button {
    width: 100px;
    height: 35px;
  }
}
</style>